package conversion.controller;


import conversion.bean.File;

import conversion.service.FileService;
import conversion.utils.FileUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
public class FileController {

    @Resource
    FileService fileService;

    @PostMapping("/saveFile")
    public String saveFile(@RequestBody File file) {


//        System.out.println(file.getFileName());

        file.setCreateTime(new Date(System.currentTimeMillis()));
        // 获取文件大小
        String fileSize = FileUtil.formatFileSize(FileUtil.estimateFileSize(file.getFileContent()));
        file.setFileSize(fileSize);
        file.setUpdateTime(new Date(System.currentTimeMillis()));

//        file.setFileSize(file.getFileContent().getBytes().toString());
        fileService.addFile(file);
        return "文件保存成功！";
    }

    @GetMapping("/getFiles")
    public Map<String, Object> getAllFiles(@RequestParam("page") int page,
                                           @RequestParam("pageSize") int pageSize,
                                           @RequestParam("search") String searchInputValue) {

//         创建用于存储结果的 Map
        Map<String, Object> resultMap = new HashMap<>();

        // 计算分页的起始索引
        int startIndex = (page - 1) * pageSize;

        List<File> allFiles;

        if (searchInputValue == null || searchInputValue.equals("")) {
            // 调用 fileService 的方法获取所有文件
            allFiles = fileService.getAllFiles();
        }else {

            allFiles = fileService.getFilesByValue(searchInputValue);
        }


        // 根据分页参数截取当前页的文件列表
        List<File> currentPageFiles = allFiles.subList(startIndex, Math.min(startIndex + pageSize, allFiles.size()));

        // 将当前页的文件列表添加到 resultMap
        resultMap.put("fileList", currentPageFiles);

        // 计算总页数
        int totalPage = (int) Math.ceil((double) allFiles.size() / pageSize);

        // 将总页数添加到 resultMap
        resultMap.put("totalPage", totalPage);

        //返回结果给前端
        return resultMap;
    }

    @GetMapping("/deleteFile")
    public void delete(@RequestParam("id") int id) {
        fileService.deleteFileById(id);

    }

    @GetMapping("/renameFile")
    public void renameFile(@RequestParam("id") int id,@RequestParam("rename") String rename) {
        File file = fileService.getFileById(id);
        System.out.println(rename);
        file.setFileName(rename);
        fileService.updateFile(file);
    }


}
